<template>
  <div class="reset-password-container">
    <el-card class="reset-card">
      <template #header>
        <span>重置密码</span>
      </template>

      <div v-if="loading">加载中...</div>
      <div v-else-if="errorMessage">
        <el-alert :title="errorMessage" show-icon type="error" />
      </div>
      <div v-else>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="用户名" prop="username">
            <el-select v-model="form.username" placeholder="请选择用户名">
              <el-option v-for="user in usernames" :key="user" :label="user" :value="user" />
            </el-select>
          </el-form-item>

          <el-form-item label="新密码" prop="newPassword">
            <el-input v-model="form.newPassword" type="password" />
          </el-form-item>

          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input v-model="form.confirmPassword" type="password" />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submit">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '@/stores/authStore'

const route = useRoute()
const router = useRouter()
const authStore = useAuthStore()

const form = ref({
  username: '',
  newPassword: '',
  confirmPassword: '',
})

const formRef = ref<FormInstance | null>(null)
const usernames = ref([])
const loading = ref(true)
const errorMessage = ref<string | null>(null)

const token = route.query.token as string

onMounted(async () => {
  try {
    const res = await authStore.findPreciseAccount({ token })
    usernames.value = res.usernames || []
    if (usernames.value.length === 1) {
      form.value.username = usernames.value[0]
    }
  } catch (e) {
    errorMessage.value = '链接无效或已过期'
    ElMessage.error(errorMessage.value)
  } finally {
    loading.value = false
  }
})

const rules = {
  username: [{ required: true, message: '请选择用户名', trigger: 'blur' }],
  newPassword: [{ required: true, message: '请输入新密码', trigger: 'blur' }],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (_: never, value: string) => {
        if (value !== form.value.newPassword) {
          return Promise.reject(new Error('两次输入密码不一致'))
        }
        return Promise.resolve()
      },
      trigger: 'blur',
    },
  ],
}

const submit = async () => {
  if (!formRef.value) return
  try {
    const valid = await formRef.value.validate()
    if (!valid) return

    await authStore.resetPasswordByToken({
      token,
      username: form.value.username,
      newPassword: form.value.newPassword,
      confirmPassword: form.value.confirmPassword,
    })
    ElMessage.success('密码重置成功！请重新登录。')
    await router.push('/login')
  } catch (e) {
    ElMessage.error('重置失败')
  }
}
</script>

<style scoped>
.reset-password-container {
  max-width: 500px;
  margin: 60px auto;
}
</style>
